<template>
  <div class="sign_wrap safe">
    <div class="banner_wrap">
      <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
        <van-swipe-item v-for="(item, index) in ad.bannerLink" :key="index">
          <div class="banner_item">
            <van-image fit="cover" :src="item.link" />
          </div>
        </van-swipe-item>
      </van-swipe>
    </div>
    <div class="detail_wrap" v-if="formDetail && formDetail.approvalStatus">
      <van-form>
        <van-field readonly label="审核状态">
          <div slot="input" :style="formDetail.approvalStatus | filterClass">
            {{ formDetail.approvalStatus | filterStatus }}
          </div>
        </van-field>
        <van-field :value="formDetail.number" readonly label="编号" />
      </van-form>
    </div>
    <div class="form_wrap">
      <div class="form-item" v-if="groupList.length">
        <div class="title-box">
          <span
            :style="{
              color: basic.theme || cfg.theme,
            }"
            class="iconfont iconzuopin"
          ></span>
          <span class="title">分组</span>
        </div>
        <van-field
          v-model="groupName"
          is-link
          readonly
          :error-message="errorGroup"
          @click="showGroup = true"
          placeholder="请先选择分组（必填项）"
        />
        <!-- <van-action-sheet
          v-model="showGroup"
          :actions="groupListSheet"
          @select="onSelectGroup"
        /> -->
        <van-popup v-model="showGroup" position="bottom">
          <van-picker
            show-toolbar
            :default-index="groupIndex"
            :columns="groupListSheet"
            @confirm="onConfirm"
            @cancel="onCancel"
          />
        </van-popup>
      </div>
      <div class="form-item">
        <div class="title-box">
          <span
            :style="{
              color: basic.theme || cfg.theme,
            }"
            class="iconfont iconzuopin"
          ></span>
          <span class="title">选手名称/作品名称</span>
        </div>
        <van-field
          v-model="addPlayerForm.name"
          :error-message="errorName"
          placeholder="请输入选手名称或作品名称"
          @input="inputName"
        />
      </div>
      <div class="form-item">
        <div class="title-box">
          <span
            :style="{
              color: basic.theme || cfg.theme,
            }"
            class="iconfont iconzuopin"
          ></span>
          <span class="title">参赛介绍</span>
        </div>
        <van-field
          v-model="addPlayerForm.introduction"
          placeholder="请输入参赛介绍"
        />
      </div>
      <div class="form-item">
        <div class="title-box">
          <span
            :style="{
              color: basic.theme || cfg.theme,
            }"
            class="iconfont iconzuopin"
          ></span>
          <span class="title">参赛图片</span>
        </div>
        <div class="commonM">
          <uploader
            :activeCover="addPlayerForm.coverLink"
            @handleSuccess="handleSuccess"
          />
        </div>
      </div>
      <div
        class="form-item"
        v-for="(item, index) in addPlayerForm.contestantAttributeValues"
        :key="index"
      >
        <div class="title-box">
          <span
            :style="{
              color: basic.theme || cfg.theme,
            }"
            class="iconfont iconzuopin"
          ></span>
          <span class="title">{{ item.name }}</span>
        </div>

        <!-- 区域文本 -->
        <template v-if="item.type === 'TEXT_AREA'">
          <van-field
            v-model="item.value"
            rows="1"
            autosize
            type="textarea"
            :error-message="item.error"
            placeholder="请输入"
            @input="inputTextArea($event, index)"
          />
        </template>
        <!-- 文本 -->
        <template v-if="item.type.indexOf('INPUT_TEXT') != -1">
          <van-field
            :error-message="item.error"
            v-model="item.value"
            placeholder="请输入"
            @input="inputText($event, index)"
          />
        </template>
        <!-- 文件上传 -->
        <template v-if="item.type === 'INPUT_FILE'">
          <div class="commonM">
            <uploader
              :fileList="addPlayerForm.contestantAttributeValues[index].value"
              @handleSuccess="handleSuccess1($event, index)"
              :multiple="true"
              :maxCount="6"
              previewSize="87px"
            />
            <div v-if="item.required && item.error" class="error-text">
              {{ item.error }}
            </div>
          </div>
        </template>
      </div>
      <div
        v-if="
          formDetail.approvalStatus !== 'WAITTING' &&
          formDetail.approvalStatus !== 'PASS'
        "
        class="footer-btn"
        @click="submit"
        :style="{ background: basic.theme || cfg.theme }"
      >
        立即提交
      </div>
    </div>
    <van-dialog
      v-model="showCode"
      title="提示"
      show-cancel-button
      :show-confirm-button="false"
    >
      <div ref="qrCodePng" id="qrCodePng">
        <vue-qr
          :text="QRcodeUrl"
          :margin="0"
          colorDark="#000"
          colorLight="#fff"
          :logoScale="0.3"
          :size="120"
        ></vue-qr>
        <span>请使用微信扫码后操作</span>
      </div>
    </van-dialog>
    <van-dialog
      v-model="showWeChatCode"
      title="提示"
      show-cancel-button
      :show-confirm-button="false"
      cancelButtonText="关闭"
      @close="handleClose"
    >
      <div id="qrWeChatCode">
        <img style="width: 140px; height: 140px" :src="wechatCodeQR" alt="" />
        <span>请先扫码关注公众号后操作</span>
      </div>
    </van-dialog>

    <footer-logo></footer-logo>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import footerLogo from "@/components/footerLogo";
import { LgetItem } from "@/utils/storage";
import cfg from "@/config";
import uploader from "@/components/Uploader";
import { isWeiXin } from "@/utils/index";
import vueQr from "vue-qr";
import { wx,wxInit } from "@/utils/jssdkInit";
export default {
  components: {
    footerLogo,
    uploader,
    vueQr,
  },
  data() {
    return {
      voteInfo: {},
      voteId: LgetItem("voteId"),
      cfg,
      addPlayerForm: {
        contestantAttributeValues: [
          // {
          //   contestantAttributeId: 0,//选手属性编号
          //   value: "string",//值 大长度为4096个字符
          // },
        ], //自己新增的表单数组
        contestantGroupId: 0, //选手组编号
        coverLink: "", //封面链接 最大长度为256个字符
        coverType: "IMAGE", //封面类型IMAGE, VIDEO
        details: "", //详情 最大长度为1024个字符
        detailsType: "TEXT", //详情类型,TEXT, LINK
        id: 0, //编号 创建时为空
        imageLink: [
          //图片链接 条目最大长度为512个字符
        ],
        introduction: "", //简介 最大长度为128个字符
        name: "", //名称 最大长度为64个字符
        voteId: LgetItem("voteId"),
      },
      currentSelectItem: "", //记录点击下拉框的索引，方便给赋值
      errorName: "",
      groupList: [],
      groupListSheet: [],
      errorGroup: "",
      groupName: "",
      showGroup: false,
      showCode: false,
      QRcodeUrl: "",
      authFollowed: false,
      showWeChatCode: true,
      wechatCodeQR: `${cfg.host}${
        cfg.baseUrl
      }/wx/qr-code/get-q-r-code?voteId=${LgetItem("voteId")}`,
      formDetail: {},
      groupIndex: 0,
    };
  },
  computed: {
    ...mapGetters("configs", {
      ad: "ad",
      basic: "basic",
      signup: "signup",
      share:'share'
    }),
  },
  filters: {
    filterStatus(val) {
      let str = "";
      switch (val) {
        case "PASS":
          str = "已通过";
          break;
        case "REFUSE":
          str = "已拒绝";
          break;
        case "WAITTING":
          str = "待审核";
          break;
        default: {
          str = "";
          break;
        }
      }
      return str;
    },
    filterClass(val) {
      let str = "";
      switch (val) {
        case "PASS":
          str = "#409EFE";
          break;
        case "REFUSE":
          str = "#FB4723";
          break;
        case "WAITTING":
          str = "#409EFF";
          break;
        default: {
          str = "";
          break;
        }
      }
      return {
        color: str,
      };
    },
  },
  created() {
    //开启先关注后报名，需要判断是否已经关注
    if (this.signup.followedSignup) {
      if (isWeiXin()) {
        this.isAuth();
      } else {
        this.showWeChatCode = false;
      }
    } else {
      this.showWeChatCode = false;
    }
    // this.getCustomForm();
    this.getGroupList();
  },
  watch: {
    authFollowed(val) {
      this.showWeChatCode = !val;
    },
  },
  mounted(){
    this.shareFn(this.share)
  },
  methods: {
     shareFn(share) {
      this.$nextTick(() => {
        wxInit()
          .then(() => {
            wx.updateAppMessageShareData({
              //分享到朋友
              title: share.title, // 分享标题
              desc: share.context, // 分享描述
              link: window.location.href.indexOf('?') != -1?window.location.href:`${window.location.href}?id=${LgetItem("voteId")}`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
              imgUrl:share.imageLink?share.imageLink:cfg.shareImg, // 分享图标
              success: () => {
                console.log("分享成功");
              },
            });
            wx.updateTimelineShareData({
              //分享到朋友圈
              title: share.title, // 分享标题
              link: window.location.href.indexOf('?') != -1?window.location.href:`${window.location.href}?id=${LgetItem("voteId")}`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
              imgUrl:share.imageLink?share.imageLink:cfg.shareImg, // 分享图标
              success: function () {
                console.log("分享成功");
              },
            });
          })
          .catch((err) => {
            console.log(err,'err');
          });
        //   toast.clear();
      });
    },
    onConfirm(item, index) {
      console.log(item, index);
      this.showGroup = false;
      this.addPlayerForm.contestantGroupId = this.groupList[index].id;
      this.groupName = item;
      this.errorGroup = "";
    },
    onCancel() {
      this.showGroup = false;
    },
    //是否关注公众号
    isAuth() {
      this.$api("sign.isAuth").then((res) => {
        this.authFollowed = res;
      });
    },
    handleClose() {
      this.isAuth();
    },
    // 获取已经提交的报名信息
    getFormInfo() {
      this.$api("player.mysignup", {
        voteId: this.voteId,
      }).then((res) => {
        console.log(res);
        if (res) {
          this.formDetail = res;
          this.addPlayerForm.name = res.name;
          this.addPlayerForm.introduction = res.introduction;
          this.addPlayerForm.coverLink = res.coverLink;
          this.addPlayerForm.contestantGroupId = res.contestantGroupId;
          console.log(this.groupList, "22");
          this.groupList.forEach((item, index) => {
            if (item.id == res.contestantGroupId) {
              this.groupName = item.name;
              this.groupIndex = index;
            }
          });
          this.getCustomForm(res.id);
        } else {
          this.getCustomForm();
        }
      });
    },
    getGroupList() {
      this.$api("player.getGroupList", {
        voteId: this.voteId,
      }).then((res) => {
        console.log(res);
        this.groupList = res;
        this.groupList.forEach((item) => {
          this.groupListSheet.push(item.name);
        });
        this.getFormInfo();
      });
    },
    submit() {
      if (isWeiXin()) {
        if (this.signup.followedSignup) {
          if (this.authFollowed) {
            if (
              (this.addPlayerForm.contestantGroupId ||
                !this.groupList.length) &&
              this.addPlayerForm.name &&
              this.addPlayerForm.contestantAttributeValues.every(
                (item) => !item.error
              )
            ) {
              console.log(this.addPlayerForm);
              const arr1 = [];
              this.addPlayerForm.contestantAttributeValues.forEach((item) => {
                arr1.push({
                  contestantAttributeId: item.contestantAttributeId,
                  value:
                    item.type == "INPUT_FILE"
                      ? JSON.stringify(item.value)
                      : item.value,
                });
              });
              this.$api("player.signup", {
                ...this.addPlayerForm,
                contestantAttributeValues: arr1,
                id: this.formDetail.id || 0,
              }).then((res) => {
                console.log(res);
                this.$toast({
                  type: "success",
                  message: "报名成功",
                  duration: 1000,
                  onClose: () => {
                    window.location.reload();
                  },
                });
              });
            } else {
              if (!this.addPlayerForm.name) {
                this.errorName = "请输入选手名称或作品名称";
              }
              if (
                this.groupList.length &&
                !this.addPlayerForm.contestantGroupId
              ) {
                this.errorGroup = "请选择分组";
              }

              this.addPlayerForm.contestantAttributeValues.forEach((item) => {
                if (item.required) {
                  if (item.type.indexOf("INPUT_TEXT") != -1 && !item.value) {
                    item.error = "请输入";
                  }
                  if (item.type === "INPUT_FILE" && !item.value) {
                    item.error = "请上传";
                  }
                }
              });
            }
          } else {
            this.showWeChatCode = true;
          }
        } else {
          if (
            (this.addPlayerForm.contestantGroupId || !this.groupList.length) &&
            this.addPlayerForm.name &&
            this.addPlayerForm.contestantAttributeValues.every(
              (item) => !item.error
            )
          ) {
            console.log(this.addPlayerForm);
            const arr1 = [];
            this.addPlayerForm.contestantAttributeValues.forEach((item) => {
              arr1.push({
                contestantAttributeId: item.contestantAttributeId,
                value:
                  item.type == "INPUT_FILE"
                    ? JSON.stringify(item.value)
                    : item.value,
              });
            });
            this.$api("player.signup", {
              ...this.addPlayerForm,
              contestantAttributeValues: arr1,
              id: this.formDetail.id || 0,
            }).then((res) => {
              console.log(res);
              this.$toast({
                type: "success",
                message: "报名成功",
                duration: 1000,
                onClose: () => {
                  window.location.reload();
                },
              });
            });
          } else {
            if (!this.addPlayerForm.name) {
              this.errorName = "请输入选手名称或作品名称";
            }
            if (
              this.groupList.length &&
              !this.addPlayerForm.contestantGroupId
            ) {
              this.errorGroup = "请选择分组";
            }

            this.addPlayerForm.contestantAttributeValues.forEach((item) => {
              if (item.required) {
                if (item.type.indexOf("INPUT_TEXT") != -1 && !item.value) {
                  item.error = "请输入";
                }
                if (item.type === "INPUT_FILE" && !item.value) {
                  item.error = "请上传";
                }
              }
            });
          }
        }
      } else {
        this.$api("vote.getqrcode", {
          id: this.voteId,
        }).then((res) => {
          this.QRcodeUrl = res;
          this.showCode = true;
        });
      }
    },
    //单张上传
    handleSuccess(list) {
      console.log(list);
      this.addPlayerForm.coverLink = list[0].url;
    },
    handleSuccess1(list, index) {
      console.log(list, index);
      const arr=[]
      list.forEach(item=>{
        arr.push({
          url:item.url
        })
      })
      this.addPlayerForm.contestantAttributeValues[index].value = arr;
      this.addPlayerForm.contestantAttributeValues[index].error = "";
    },
    //获取自定义表单列表,自己添加了哪些表单
    getCustomForm(id) {
      this.$api("vote.getForm", {
        voteId: this.voteId,
      }).then((res) => {
        console.log(res);
        const list = [];
        if (res.length) {
          if (id) {
            this.$api("player.getPlayerContestantById", {
              contestantId: id, //选手id
              voteId: this.voteId,
            }).then((ele1) => {
              res.forEach((item) => {
                if (!item.disabled) {
                  list.push({
                    contestantAttributeId: item.id, //属性id
                    value: item.type === "INPUT_FILE"?JSON.parse(ele1[item.code]):ele1[item.code],
                    name: item.name,
                    type: item.type,
                    required: item.required,
                    error: "",
                  });
                }
                this.addPlayerForm.contestantAttributeValues = list;
                console.log(list);
              });
            });
          } else {
            res.forEach((item) => {
              if (item.type === "INPUT_FILE") {
                item.defaultValue = [];
              }
              if (!item.disabled) {
                list.push({
                  contestantAttributeId: item.id, //属性id
                  value: item.defaultValue,
                  name: item.name,
                  type: item.type,
                  required: item.required,
                  error: "",
                });
              }
            });
            this.addPlayerForm.contestantAttributeValues = list;
            console.log(list);
          }
        }
      });
    },
    onSelect(item) {
      console.log(item);
      this.addPlayerForm.contestantAttributeValues[
        this.currentSelectItem
      ].value = item.name;

      this.addPlayerForm.contestantAttributeValues[
        this.currentSelectItem
      ].error = "";
      this.currentSelectItem = "";
    },
    handleSelect(index) {
      this.currentSelectItem = index;
    },
    changeCheckBox(arr, index) {
      if (arr.length) {
        this.addPlayerForm.contestantAttributeValues[index].error = "";
      }
    },
    inputName(val) {
      if (val) {
        this.errorName = "";
      }
    },
    inputTextArea(val, index) {
      if (val) {
        this.addPlayerForm.contestantAttributeValues[index].error = "";
      }
    },
    inputText(val, index) {
      if (val) {
        this.addPlayerForm.contestantAttributeValues[index].error = "";
      }
    },
    onSelectGroup(item, index) {
      console.log(item);
      this.showGroup = false;
      this.addPlayerForm.contestantGroupId = this.groupList[index].id;
      this.groupName = item.name;
      this.errorGroup = "";
    },
  },
};
</script>
<style lang="scss" scoped>
.sign_wrap {
  width: 100%;
  min-height: 100vh;
  position: relative;
  font-size: 14px;
  .banner_wrap {
    .banner_item {
      font-size: 0;
      ::v-deep.van-image {
        width: 100%;
        height: 200px;
      }
    }
  }
  .detail_wrap {
    background: #fff;
    margin: 10px 10px 0;
    border-radius: 4px;
    padding: 5px;
  }
  .form_wrap {
    background: #fff;
    padding: 30px 20px;
    margin: 10px 10px 0;
    border-radius: 4px;
    .form-item {
      border-bottom: 1px solid #999;
      margin-bottom: 30px;
      .title-box {
        display: flex;
        align-items: center;
        .title {
          font-weight: 500;
          font-size: 16px;
          margin-left: 5px;
        }
      }
      .commonM {
        margin: 15px;
      }
      .error-text {
        color: #ee0a24;
        font-size: 12px;
        line-height: 24px;
      }
    }
    .footer-btn {
      width: 100px;
      height: 40px;
      margin: 0 auto;
      border-radius: 10px;
      text-align: center;
      line-height: 40px;
      color: #fff;
    }
  }
  #qrCodePng {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px 0;
    flex-direction: column;
    span {
      margin-top: 15px;
      color: #999;
      font-size: 12px;
    }
  }
  #qrWeChatCode {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px 0;
    flex-direction: column;
    span {
      margin-top: 15px;
      color: #999;
      font-size: 12px;
    }
  }
}
</style>